/**
 * 基础菜单 商品管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品发货</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <div style="margin-top:20px;margin-bottom:10px;">
      
        <el-button type="primary"  @click="handleEdit()" round>创建发货订单</el-button>
        <el-button type="success" round @click="exportData()">导出发货单</el-button>
        <!-- <el-button type="warning" round @click=" InventorydetailsEdit()">编辑</el-button>  -->
        <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.shipment_No" placeholder="请输入发货单号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    </div>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column align="center" prop="shipment_No" label="发货单号" width="160">
      </el-table-column>
      <el-table-column align="center" prop="customer_Name" label="客户名称" width="160">
      </el-table-column>
      <el-table-column align="center" prop="material_code" label="产品编码" width="160">
      </el-table-column>
      <el-table-column align="center" prop="product_name" label="产品名称" width="160">
      </el-table-column>
      <el-table-column align="center" prop="production_type" label="产品分类" width="160">
      </el-table-column>
      <el-table-column align="center" prop="product_model" label="产品型号" width="160">
      </el-table-column>
      <el-table-column align="center" prop="production_brand" label="产品品牌" width="160">
      </el-table-column>
      <el-table-column align="center" prop="shipped_Qty" label="发货数量" width="160">
      </el-table-column>
       <el-table-column align="center" prop="warehousename" label="发货仓库" width="160">
      </el-table-column>
      <el-table-column align="center" prop="sender" label="发货人" width="160">
      </el-table-column>
       <el-table-column align="center" prop="delivery_times" label="发货时间" width="160">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="160">
        <template slot-scope="scope">
          <el-button size="mini" disabled @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="请选择订单" prop="order_num">
          <!-- <el-select v-model="editForm.order_num">
            <el-option v-for="item in order_numdata" :key="item.id" :value="item.order_num" :label="item.order_num"/>
          </el-select> -->
          <el-input size="small" v-model="editForm.order_num" @focus="addOrder" auto-complete="off" placeholder="请输入发货单号"></el-input>
        </el-form-item>
        <el-form-item label="发货单号" prop="shipment_No">
          <el-input size="small" v-model="editForm.shipment_No" :disabled="true" auto-complete="off" placeholder="请输入发货单号"></el-input>
        </el-form-item>
        <el-form-item label="产品编码" prop="material_code">
          <el-select v-model="editForm.material_code" filterable>
            <el-option v-for="item in material_codeData" :key="item.material_code" :value="item.material_code" :label="item.material_code"/>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehousename">
          <el-select v-model="editForm.warehousename" filterable>
            <el-option v-for="item in warehouseData" :key="item.id" :value="item.warehousename" :label="item.warehousename"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="customer_Name">
          <el-input size="small" v-model="editForm.customer_Name" auto-complete="off" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="发货数量" prop="shipped_Qty">
          <el-input size="small" v-model="editForm.shipped_Qty" auto-complete="off" placeholder="请输入发货数量"></el-input>
        </el-form-item>
         <el-form-item label="发货地址" prop="address">
          <el-input size="small" v-model="editForm.address" auto-complete="off" placeholder="请输入发货地址"></el-input>
        </el-form-item>
        <el-form-item label="发货人" prop="sender">
          <el-input size="small" v-model="editForm.sender" auto-complete="off" placeholder="请输入发货人姓名"></el-input>
        </el-form-item>
         <!-- <el-form-item label="发货人" prop="sender">
          <el-select v-model="editForm.sender">
            <el-option v-for="item in senderData" :key="item.id" :value="item.sender" :label="item.sender"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="发货时间" prop="delivery_times">
          <el-date-picker
            v-model=" editForm.delivery_times"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
    </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 显示订单 -->
    <el-dialog :title="title" :visible.sync="OrderVisible" width="60%"  @click="closeDialog">
      <el-table
    :data="order_numdata"
    height="250"
    border
    style="width: 100%"
    highlight-current-row @current-change="handleCurrentChange">
    <el-table-column
      prop="order_num"
      label="订单编号"
      width="180">
    </el-table-column>
    <el-table-column
      prop="order_status"
      label="订单状态"
      width="160">
    </el-table-column>
    <el-table-column
      prop="material_code"
      label="产品编码"
       width="160">
    </el-table-column>
     <el-table-column
      prop="product_name"
      label="产品名称"
       width="160">
    </el-table-column>
     <el-table-column
      prop="order_account"
      label="发货数量"
       width="160">
    </el-table-column>
     <el-table-column
      prop="order_client"
      label="客户名字"
       width="160">
    </el-table-column>
  </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeorder">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitorder()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import{v4} from 'uuid'
import Pagination from '../../components/Pagination'
export default {
  data() {
     //校验器
    var checknum = (rule, value, callback) => {
      if(this.editForm.warehouse_num>=value&&value>0){
        callback()
      }else{
        if(this.editForm.warehouse_num<value){
            callback(new Error('库存不足'));
        }else{
          callback(new Error('请不要乱输'));
        }
        
      }

    };
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      OrderVisible:false,//订单页面显示与隐藏
      title: '添加',
      editForm: {
        address:"",
        warehouse_num:"",
        order_num:'',
        id:'',
       shipment_No:"",
        material_code:"",
       warehousename:"",
       customer_Name:"",
       shipped_Qty:"",
       delivery_times:"",
       sender:"",
       order_num:'',
        token: localStorage.getItem('logintoken')
      },
      // rules表单验证
      rules: {
         shipped_Qty: [
          { required: true, message: '请输入发货数量', trigger: 'blur' },
          {validator: checknum, trigger: 'change' }
        ],
         sender: [
          { required: true, message: '请输入发货人姓名', trigger: 'blur' },
        ],
          order_num: [
          { required: true, message: '请选择订单编号', trigger: 'change' },
        ],
          material_code: [
          { required: true, message: '请输入产品编码', trigger: 'blur' },
        ],
         customer_Name: [
          { required: true, message: '请输入客户名字', trigger: 'blur' },
        ],
        warehousename: [
          { required: true, message: '请输入仓库名字', trigger: 'blur' },
        ],
       delivery_times: [
          { required: true, message: '请输入发货时间', trigger: 'blur' },
        ],
         address: [
          { required: true, message: '请输入发货地址', trigger: 'blur' },
        ],
      },
      formInline: {
        shipment_No:"",
        page: 1,
        limit: 10,
        varLable: '',
        varName: '',
        token: localStorage.getItem('logintoken')
      },
      // 删除部门
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      warehouseData: [], //仓库数据
      material_codeData:[],//编码数据
      order_numdata:[],//获取订单编码
      senderData:[],//获取用户信息
      
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //导出发货订单
    exportData(){
      this.$axios.get("/api/productionwarehouse/export",{
        responseType: 'blob'
      }).then(response=> {
        //通过header中获取返回的文件名称
        let fileName = response.headers['content-disposition'].split(";")[1].split("filename=")[1]
        let blob = new Blob([response.data], { type: "application/vnd.ms-excel" })
        let downloadElement = document.createElement("a")
        var href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        //指定下载的文件的名称，切记进行decode
        downloadElement.download = decodeURI(fileName)
        document.body.appendChild(downloadElement)
        downloadElement.click()
        //移除临时创建对象，释放资源
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      });
    },
    //获取订单选中的数据
      handleCurrentChange(val) {
      this.currentRow = val;
    },
    //关闭订单弹框
    closeorder(){
      this.OrderVisible=false;
    },
    //弹出订单页面
    addOrder(){
         this.OrderVisible=true;
          this.getorder_numdata();
    },
    //订单保存页面
    submitorder(){
      let u = localStorage.getItem("userdata");
        let user = JSON.parse(u)
        this.editForm.sender=user.name;
        this.editForm.order_num=this.currentRow.order_num;
        this.editForm.material_code=this.currentRow.material_code;
        this.editForm.customer_Name=this.currentRow.order_client;
        this.$axios.get('/api/productionwarehouse/findPW/'+this.currentRow.material_code).then(res=>{
              this.editForm.warehousename=res.data.data.warehousename;
              this.editForm.warehouse_num=res.data.data.warehouse_num;
               this.editForm.shipped_Qty=this.currentRow.order_account;
        }).catch()
        console.log(this.currentRow.order_client)
        let name = this.currentRow.order_client
          this.$axios.get('/api/merchants/name/'+encodeURI(encodeURI(name))).then(res=>{
             this.editForm.address=res.data.data.address;
        }).catch()
        this.OrderVisible=false;
    },
    //获取仓库数据
    getWarehouseData(){
      this.$axios.get('/api/warehouse/findAll').then(res=>{
        //console.log(res)
         this. warehouseData=res.data.data
      }).catch();
    },
    //获取编码数据
    getmaterial_codeData(){
        this.$axios.get("/api/production/production").then(res=>{
              //console.log(res)
              this.material_codeData=res.data.data
        }).catch()
    
    },
    //获取未发货订单
    getorder_numdata(){
        this.$axios.get('/api/productionwarehouse/findOrder').then(res=>{
          console.log(res)
         this.order_numdata=res.data.data
         let numdata=res.data.data
         for(const i in numdata){
              numdata[i].order_status="待发货"
         }
        }).catch()
    },
    
    // 获取公司列表
    getdata() {
      this.loading = true
      // 模拟数据开始
     this.$axios.get('/api/productionwarehouse/findAlldelivery_record/'+this.pageparm.currentPage+'/'+this.pageparm.pageSize)
        .then(res => {
          console.log(res)
          this.loading = false
          if (res.code==200) {
            this.$message({
              type: 'info',
              message: res.message
            })
          } else {
            this.listData = res.data.data.list
            // 分页赋值
            this.pageparm.total = res.data.data.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage
      this.pageparm.pageSize = parm.pageSize
      this.getdata(this.formInline)
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    // 根据发货订单查询
    search() {
      this.$axios.get('/api/productionwarehouse/findShipment_No/'+this.formInline.shipment_No).then(res=>{
        this.pageparm.total=res.data.data.length
         this.listData=res.data.data
      }).catch()
     
    },
    //显示编辑界面
    handleEdit: function(row) {
      this.editFormVisible = true
      this.getWarehouseData();
      this.getmaterial_codeData();
      
       if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.editForm.shipment_No = row.shipment_No
        this.editForm.material_code = row.material_code
        this.editForm.warehousename = row.warehousename
        this.editForm.customer_Name=row.customer_Name
        this.editForm.shipped_Qty=row.shipped_Qty
        this.editForm. delivery_times=row. delivery_times
        this.editForm. sender=row. sender
      } else {
        this.title = '添加'
        this.editForm.order_num=""
         this.editForm.shipment_No ="WN-"+v4()
        this.editForm.material_code = ""
        this.editForm.warehousename = ""
        this.editForm.customer_Name=""
        this.editForm.shipped_Qty=""
        this.editForm. delivery_times=""
        this.editForm. sender=""
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editForm) {
       this.$refs[editForm].validate(valid => {
         if (!valid) {
          this.$message.error("请填写正确的信息！");
        }else{
      if(this.title==="添加"){
        this.$axios.post('/api/productionwarehouse/add',this.editForm).then(res=>{
                 this.editFormVisible = false;
                if (res.data.code==200) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '订单创建成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
      }).catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('新增订单，请稍后再试！')
            })
            //修改库存数量
        this.$axios.put('/api/productionwarehouse/update',this.editForm).then(res=>{

        }).catch()
        //修改订单状态
        this.$axios.put('/api/productionwarehouse/updateOrderStatus',this.editForm).then(res=>{

        }).catch()

      }else{
        this.$axios.put('/api/productionwarehouse/productionwarehouse',this.editForm).then(res=>{
            //关闭弹窗
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "修改成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }


        }).catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('修改订单，请稍后再试！')
            })
      }
       }
        })
      
    },
    // 删除公司
    deleteUser(row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
         this.$axios.delete('/api/productionwarehouse/delete/'+row.shipment_No)
            .then(res => {
              if (res.data.code==200) {
                this.$message({
                  type: 'success',
                  message: '订单已删除!'
                })
                this.getdata()
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('订单删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 
 